<template>
  <div class="page-container">
    <button class="back-button" @click="goToHome">
      <span class="icon-arrow-left"></span>
      返回首页
    </button>
    
    <div class="header-actions">
      <h1>设备分配</h1>
      <button class="primary-btn" @click="showAssignModal = true">
        <span class="icon-plus"></span> 新增分配
      </button>
    </div>
    
    <p>这里是设备分配页面，您可以分配设备给团队成员使用。</p>
    
    <div class="card">
      <div class="search-filter">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索设备或人员..." 
          class="search-input"
        >
        <select v-model="filterStatus" class="filter-select">
          <option value="">所有状态</option>
          <option value="已分配">已分配</option>
          <option value="已归还">已归还</option>
        </select>
      </div>
      
      <table class="assignment-table">
        <thead>
          <tr>
            <th>分配编号</th>
            <th>设备名称</th>
            <th>设备编号</th>
            <th>分配给</th>
            <th>分配日期</th>
            <th>预计归还</th>
            <th>实际归还</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="assignment in filteredAssignments" :key="assignment.id" class="table-row">
            <td>{{ assignment.code }}</td>
            <td>{{ assignment.deviceName }}</td>
            <td>{{ assignment.deviceCode }}</td>
            <td>{{ assignment.assignee }}</td>
            <td>{{ assignment.assignDate }}</td>
            <td>{{ assignment.expectedReturnDate }}</td>
            <td>{{ assignment.actualReturnDate || '-' }}</td>
            <td>
              <span :class="`status-badge ${assignment.statusClass}`">
                {{ assignment.status }}
              </span>
            </td>
            <td class="action-buttons">
              <button 
                class="btn-return" 
                @click="returnDevice(assignment)"
                v-if="assignment.status === '已分配'"
              >
                标记归还
              </button>
              <button class="btn-view" @click="viewAssignment(assignment)">详情</button>
            </td>
          </tr>
          <tr v-if="filteredAssignments.length === 0">
            <td colspan="9" class="no-data">暂无分配记录</td>
          </tr>
        </tbody>
      </table>
      
      <div class="pagination">
        <button 
          class="page-btn" 
          :disabled="currentPage === 1" 
          @click="currentPage--"
        >
          上一页
        </button>
        <span class="page-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页
        </span>
        <button 
          class="page-btn" 
          :disabled="currentPage === totalPages" 
          @click="currentPage++"
        >
          下一页
        </button>
      </div>
    </div>
    
    <!-- 分配设备弹窗 -->
    <div v-if="showAssignModal" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h3>设备分配</h3>
          <button class="close-btn" @click="showAssignModal = false">&times;</button>
        </div>
        <div class="modal-body">
          <form class="assignment-form">
            <div class="form-group">
              <label>选择设备 <span class="required">*</span></label>
              <select v-model="currentAssignment.deviceId" required @change="updateDeviceInfo">
                <option value="">-- 请选择设备 --</option>
                <option 
                  v-for="device in availableDevices" 
                  :key="device.id" 
                  :value="device.id"
                >
                  {{ device.name }} ({{ device.code }})
                </option>
              </select>
            </div>
            <div class="form-group">
              <label>分配给 <span class="required">*</span></label>
              <select v-model="currentAssignment.assigneeId" required>
                <option value="">-- 请选择人员 --</option>
                <option 
                  v-for="user in users" 
                  :key="user.id" 
                  :value="user.id"
                >
                  {{ user.name }} ({{ user.department }})
                </option>
              </select>
            </div>
            <div class="form-group">
              <label>分配日期 <span class="required">*</span></label>
              <input type="date" v-model="currentAssignment.assignDate" required>
            </div>
            <div class="form-group">
              <label>预计归还日期</label>
              <input type="date" v-model="currentAssignment.expectedReturnDate">
            </div>
            <div class="form-group">
              <label>分配原因</label>
              <textarea 
                v-model="currentAssignment.reason" 
                rows="3"
                placeholder="请输入分配原因..."
              ></textarea>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="showAssignModal = false">取消</button>
          <button class="save-btn" @click="saveAssignment">确认分配</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DeviceAssignment',
  data() {
    return {
      searchQuery: '',
      filterStatus: '',
      currentPage: 1,
      pageSize: 10,
      showAssignModal: false,
      currentAssignment: {
        deviceId: '',
        assigneeId: '',
        assignDate: new Date().toISOString().split('T')[0],
        expectedReturnDate: '',
        reason: ''
      },
      // 模拟可用设备数据（仅正常状态且未分配的）
      availableDevices: [
        { id: 1, code: 'DEV-001', name: '笔记本电脑', model: 'ThinkPad X1', status: '正常' },
        { id: 3, code: 'DEV-003', name: '投影仪', model: 'Epson CB-X06', status: '正常' },
      ],
      // 模拟用户数据
      users: [
        { id: 1, name: '张三', department: '研发部' },
        { id: 2, name: '李四', department: '市场部' },
        { id: 3, name: '王五', department: '财务部' },
        { id: 4, name: '赵六', department: '行政部' },
      ],
      // 分配记录
      assignments: [
        { 
          id: 1, 
          code: 'ASN-001', 
          deviceId: 2,
          deviceName: '打印机',
          deviceCode: 'DEV-002',
          assigneeId: 2,
          assignee: '李四',
          assignDate: '2023-05-10',
          expectedReturnDate: '2023-05-20',
          actualReturnDate: '',
          status: '已分配',
          statusClass: 'status-assigned'
        },
        { 
          id: 2, 
          code: 'ASN-002', 
          deviceId: 4,
          deviceName: '扫描仪',
          deviceCode: 'DEV-004',
          assigneeId: 1,
          assignee: '张三',
          assignDate: '2023-04-15',
          expectedReturnDate: '2023-04-30',
          actualReturnDate: '2023-04-28',
          status: '已归还',
          statusClass: 'status-returned'
        }
      ]
    };
  },
  computed: {
    filteredAssignments() {
      return this.assignments
        .filter(assignment => 
          (this.searchQuery === '' || 
           assignment.deviceName.includes(this.searchQuery) || 
           assignment.deviceCode.includes(this.searchQuery) ||
           assignment.assignee.includes(this.searchQuery)) &&
          (this.filterStatus === '' || assignment.status === this.filterStatus)
        )
        .slice(
          (this.currentPage - 1) * this.pageSize,
          this.currentPage * this.pageSize
        );
    },
    totalPages() {
      const filteredCount = this.assignments.filter(assignment => 
        (this.searchQuery === '' || 
         assignment.deviceName.includes(this.searchQuery) || 
         assignment.deviceCode.includes(this.searchQuery) ||
         assignment.assignee.includes(this.searchQuery)) &&
        (this.filterStatus === '' || assignment.status === this.filterStatus)
      ).length;
      return Math.ceil(filteredCount / this.pageSize);
    }
  },
  methods: {
    goToHome() {
      this.$router.push('/home');
    },
    updateDeviceInfo() {
      const device = this.availableDevices.find(d => d.id === this.currentAssignment.deviceId);
      if (device) {
        this.currentAssignment.deviceName = device.name;
        this.currentAssignment.deviceCode = device.code;
      }
    },
    saveAssignment() {
      // 验证必填项
      if (!this.currentAssignment.deviceId || !this.currentAssignment.assigneeId || !this.currentAssignment.assignDate) {
        alert('请填写必填项');
        return;
      }
      
      // 获取被分配人姓名
      const assignee = this.users.find(u => u.id === this.currentAssignment.assigneeId);
      
      // 创建新分配记录
      const newAssignment = {
        id: this.assignments.length + 1,
        code: `ASN-${(this.assignments.length + 1).toString().padStart(3, '0')}`,
        ...this.currentAssignment,
        assignee: assignee ? assignee.name : '',
        actualReturnDate: '',
        status: '已分配',
        statusClass: 'status-assigned'
      };
      
      this.assignments.unshift(newAssignment);
      
      // 从可用设备列表中移除已分配的设备
      this.availableDevices = this.availableDevices.filter(
        d => d.id !== this.currentAssignment.deviceId
      );
      
      // 重置表单并关闭弹窗
      this.resetAssignmentForm();
      this.showAssignModal = false;
    },
    resetAssignmentForm() {
      this.currentAssignment = {
        deviceId: '',
        assigneeId: '',
        assignDate: new Date().toISOString().split('T')[0],
        expectedReturnDate: '',
        reason: ''
      };
    },
    returnDevice(assignment) {
      const confirmReturn = confirm(`确定要标记 ${assignment.deviceName} 为已归还吗？`);
      if (confirmReturn) {
        const index = this.assignments.findIndex(a => a.id === assignment.id);
        if (index !== -1) {
          this.assignments[index].status = '已归还';
          this.assignments[index].statusClass = 'status-returned';
          this.assignments[index].actualReturnDate = new Date().toISOString().split('T')[0];
          
          // 将设备添加回可用设备列表
          const device = {
            id: assignment.deviceId,
            code: assignment.deviceCode,
            name: assignment.deviceName,
            status: '正常'
          };
          this.availableDevices.push(device);
        }
      }
    },
    viewAssignment(assignment) {
      console.log('查看分配详情:', assignment);
      // 可以实现查看详情的逻辑
    }
  }
};
</script>

<style scoped>
.page-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
}

.primary-btn {
  background: #2ecc71;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: background 0.3s;
}

.primary-btn:hover {
  background: #27ae60;
}

.card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.search-filter {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input, .filter-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  flex: 1;
  max-width: 300px;
}

.assignment-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.assignment-table th, .assignment-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

.assignment-table th {
  background: #f8f9fa;
  font-weight: 600;
}

.table-row:hover {
  background: #f9f9f9;
  transition: background 0.2s;
}

.status-badge {
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-assigned {
  background: #e8f4fd;
  color: #3498db;
}

.status-returned {
  background: #eafaf1;
  color: #27ae60;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.btn-view, .btn-return {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
}

.btn-view {
  background: #e3f2fd;
  color: #1976d2;
}

.btn-return {
  background: #ffebee;
  color: #c62828;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

.page-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.page-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.page-info {
  color: #666;
}

.no-data {
  text-align: center;
  padding: 40px;
  color: #999;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 600px;
  max-width: 90%;
  box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 20px;
}

.assignment-form {
  display: grid;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  font-weight: 500;
  font-size: 14px;
}

.required {
  color: #e74c3c;
}

.form-group input, 
.form-group select,
.form-group textarea {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-group textarea {
  resize: vertical;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn, .save-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #ddd;
}

.save-btn {
  background: #3498db;
  color: white;
  border-color: #3498db;
}

.cancel-btn:hover {
  background: #f5f5f5;
}

.save-btn:hover {
  background: #2980b9;
}

/* 继承并复用返回按钮样式 */
.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 20px;
  font-weight: 500;
}

.back-button:hover {
  background: #2980b9;
  transform: translateY(-2px);
}
</style>